<?php

namespace App\Http\Controllers\Api;

use App\Exceptions\MyException;
use App\Http\Controllers\Controller;
use Exception;
use GuzzleHttp\Client;
use Illuminate\Http\Request;

class ProxyController extends Controller
{
    // 注册代理
    public function index($passer, $path, Request $request)
    {
        $passerClass = config('proxy.passer.' . $passer);
        if (!$passerClass) {
            return response()->json(['proxy_message' => 'passer not found', 'proxy_code' => 404]);
        }

        try {
            $res = (new $passerClass($request->method(), $path, $request->header(), $request->all()))->handle();
        } catch (Exception $e) {
            return response()->json(['proxy_message' => $e->getMessage(), 'proxy_code' => $e->getCode()]);
        }

        return response($res->getBody(), $res->getStatusCode(), $res->getHeaders());
    }

    // 通用代理
    public function pass(Request $request)
    {
        try {
            my_validator([
                'request_method'  => 'required',
                'request_url'     => 'required',
                'request_headers' => 'required',
                'body_type'       => 'required',
                'body_data'       => 'required',
            ]);

            $res = (new Client())->request($request->request_method, $request->request_url, [
                'headers' => $request->request_headers,
                $request->body_type => $request->body_data,
            ]);

        } catch (MyException $e) {
            return response()->json(['message' => $e->getMessage()]);
        }

        return response($res->getBody(), $res->getStatusCode(), $res->getHeaders());
    }
}
